package com.sj.purchase.modules.cost.config.task.synchronizedata;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sj.purchase.modules.cost.domain.imei.ImeiId;
import com.sj.purchase.modules.cost.repository.imei.ImeiRepository;
import com.sj.purchase.modules.cost.domain.imei.Imei;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 串码
 * Created by yangrd on 2017/7/22.
 */
@Component
public class IMEITask {

    private static final Logger logger = LoggerFactory.getLogger(IMEITask.class);

    @Value("${sj.wms}")
    private String wmsApi;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ImeiRepository imeiRepository;

    /**
     * @param day yyyy/MM/dd
     */
    @Transactional
    public void synchronizeIMEI(String day) {
        day = day.replaceAll("/", "-");
        String inImeiUrl = wmsApi + "/imei/getInImei";
        String outImeiUrl = wmsApi + "/imei/getOutImei";
        saveImei(inImeiUrl, day, Imei.ImeiType.IN);
        saveImei(outImeiUrl, day, Imei.ImeiType.OUT);
        logger.debug("[ saveImei ]=>dateTime: {}", day);
    }


    /**
     * @param url
     * @param day 格式 yyyy-mm-dd
     */
    private void saveImei(String url, String day, final Imei.ImeiType imeiType) {
        String imeiArrayStr = restTemplate.getForObject(url + "?dateTime=" + day, String.class);
        JSONArray imeiArray = JSON.parseArray(imeiArrayStr);
        List<Imei> imeiList = imeiArray.stream().map(o -> imeiCoversion((JSONObject) o)).peek(imei -> imei.setImeiType(imeiType)).collect(Collectors.toList());
        imeiRepository.save(imeiList);
    }

    //imei
    private Imei imeiCoversion(JSONObject jsonObject) {
        String orderNo = jsonObject.getString("oddNum");
        Date orderDate = jsonObject.getDate("dateTime");
        String skuNo = jsonObject.getString("skuNo");
        String imeiNo = jsonObject.getString("imei");
        ImeiId imeiId = new ImeiId();
        imeiId.setImei(imeiNo);
        imeiId.setOrderNo(orderNo);
        Imei imei = new Imei();
        imei.setId(imeiId);
        imei.setCreateDate(orderDate);
        imei.setSku(skuNo);
        //入库或出库需要自己定义
        return imei;
    }

}
